package com.naruto.thinkmgr.configuration;

import com.naruto.thinkmgr.bean.Permission;
import com.naruto.thinkmgr.bean.Role;
import com.naruto.thinkmgr.bean.User;
import com.naruto.thinkmgr.service.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Transformer;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class ShiroRealm extends AuthorizingRealm {

    private final static Logger logger = LoggerFactory.getLogger(ShiroRealm.class);

    @Autowired
    private CredentialsMatcher credentialsMatcher;


    public ShiroRealm() {
        logger.info("create ShiroRealm");
    }


    //    @Reference(version = "1.0.0", check = false)
//    @InterfaceMethods(methods = {@Method(name = "getUserByName", retries = 2, timeout = 3000)})
    @Autowired
    @Lazy
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.debug("授权");
        User user = (User) principalCollection.getPrimaryPrincipal();//获取主要身份信息
        int userId = user.getUserId();
        //从数据库获取该用户角色信息
        Collection<Role> allRolesByUserId = userService.getAllRolesByUserId(userId);
//        从数据库获取该用户资源权限
        Collection<Permission> allPermissionsByUserId = userService.getAllPermissionsByUserId(userId);
        Collection<String> roles = CollectionUtils.collect(allRolesByUserId, new Transformer<Role, String>() {
            @Override
            public String transform(Role role) {
                return role.getRoleName();
            }
        });
        Collection<String> permissions = CollectionUtils.collect(allPermissionsByUserId, new Transformer<Permission, String>() {
            @Override
            public String transform(Permission permission) {
                return permission.getPermissionName();
            }
        });

        SimpleAuthorizationInfo sazi = new SimpleAuthorizationInfo();
        sazi.addRoles(roles);
        sazi.addStringPermissions(permissions);
        return sazi;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.debug("认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = this.userService.getUserByName(token.getUsername());
        if (user == null) {
            throw new UnknownAccountException("账号不存在");
        }
        // 还可以检查账号是否可用

        ByteSource salt = ByteSource.Util.bytes(user.getUserName());
        String password = user.getPassword();
        user.setPassword(null);//避免泄漏password
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, password, salt, getName());
        return authenticationInfo;
    }

    @Override
    public CredentialsMatcher getCredentialsMatcher() {
        return this.credentialsMatcher;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
